import { useNavigate, Link } from "react-router-dom";
import { useDispatch } from "react-redux";
import { useState, useEffect } from "react";
import request from "../../request";
import {
  ArticleDeleteResult,
  ArticleFavoriteResult,
} from "../../store/module/articleSlice";
import { notification } from "antd";

// 自己的文章 删除和编辑 --- 路由
const favorite = "btn btn-outline-danger";
const notFavorite = "btn btn-outline-success";

const ArticleAction = (props) => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { article, currentUser } = props;
  const { slug, author } = article;
  const [api, contextHolder] = notification.useNotification();

  // 定义通知状态
  const [notificationConfig, setNotificationConfig] = useState(null);

  // 删除文章
  const deleteArticle = async (slug) => {
    try {
      const result = await request.article.delete(slug);
      if (result.status === 1) {
        // 设置成功通知和跳转
        setNotificationConfig({
          type: "info",
          message: "删除成功",
          description: result.message,
          placement: "topLeft",
          duration: 1,
          onClose: () => navigate("/"),
        });
      } else {
        // 设置失败通知
        setNotificationConfig({
          type: "info",
          message: "删除失败",
          description: result.message,
          placement: "topLeft",
          duration: 1,
        });
      }
    } catch (error) {
      dispatch(ArticleDeleteResult(String(error)));
    }
  };

  const favoriteArticle = async (slug) => {
    try {
      const result = await request.article.favorite(slug);
      if (result.status === 1) {
        dispatch(ArticleFavoriteResult(result.data));
        setNotificationConfig({
          type: "info",
          message: "关注成功",
          description: result.message,
          placement: "topLeft",
          duration: 2,
        });
      }
    } catch (error) {
      dispatch(ArticleDeleteResult({ errors: String(error) }));
    }
  };

  const unFavoriteArticle = async (slug) => {
    try {
      const result = await request.article.unfavorite(slug);
      if (result.status === 1) {
        dispatch(ArticleFavoriteResult(result.data));
        setNotificationConfig({
          type: "info",
          message: "取消关注成功",
          description: result.message,
          placement: "topLeft",
          duration: 2,
        });
      }
    } catch (error) {
      dispatch(ArticleDeleteResult({ errors: String(error) }));
    }
  };

  // 处理通知的副作用钩子
  useEffect(() => {
    if (notificationConfig) {
      const { type, onClose, ...config } = notificationConfig;
      api[type]({
        ...config,
        onClose: () => {
          if (onClose) onClose();
          setNotificationConfig(null); // 重置通知状态
        },
      });
    }
  }, [notificationConfig, api]);

  if (currentUser) {
    const isMe =
      currentUser && author && currentUser.username === author.username;
    if (isMe) {
      return (
        <span>
          {contextHolder}
          <button className="btn btn-outline-success">
            <Link to={`/article/edit/${slug}`}>
              <i className="iconfont icon-zhuanchezhuanyongbeifen"></i>编辑
            </Link>
          </button>{" "}
          <button
            onClick={() => {
              deleteArticle(slug);
            }}
            className="btn btn-outline-danger"
          >
            <i className="iconfont icon-denglong"></i> 删除
          </button>
        </span>
      );
    } else {
      return (
        <button
          className={article.favorited ? favorite : notFavorite}
          onClick={() => {
            if (article.favorited) {
              unFavoriteArticle(slug);
            } else {
              favoriteArticle(slug);
            }
          }}
        >
          {contextHolder}
          <i className="iconfont icon-xihuan"></i>喜欢个数：
          {article.favoriteCount}
        </button>
      );
    }
  } else {
    return (
      <button
        className="btn btn-outline-danger"
        onClick={() => {
          navigate("/login");
        }}
      >
        {contextHolder}
        <i className="iconfont icon-xihuan"></i>喜欢
      </button>
    );
  }
};

export default ArticleAction;
